<template>
  <div class="template-manager-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>模板管理</span>
        </div>
      </template>
      
      <!-- 搜索和上传区域 -->
      <div class="action-section">
        <div class="search-area">
          <el-input
            v-model="searchKeyword"
            placeholder="请输入文件名进行模糊查询"
            clearable
            style="width: 300px;"
            @keyup.enter="handleSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
          <el-button type="primary" @click="handleSearch" :loading="loading">
            搜索
          </el-button>
        </div>
        
        <div class="upload-area">
          <el-upload
            ref="uploadRef"
            :action="uploadAction"
            :before-upload="beforeUpload"
            :http-request="customUpload"
            :show-file-list="false"
            accept=".doc,.docx,.xls,.xlsx,.ppt,.pptx,.pdf"
          >
            <el-button type="success">
              <el-icon><Upload /></el-icon>
              上传模板
            </el-button>
          </el-upload>
        </div>
      </div>
      
      <!-- 模板列表 -->
      <div class="table-section">
        <el-table 
          :data="templateList" 
          v-loading="loading"
          style="width: 100%"
          stripe
        >
          <el-table-column prop="id" label="ID" width="80" align="center" />
          <el-table-column prop="file_name" label="文件名" min-width="300" />
          <el-table-column prop="upload_time" label="上传时间" width="180" align="center">
            <template #default="scope">
              {{ formatDateTime(scope.row.upload_time) }}
            </template>
          </el-table-column>
          <el-table-column prop="delflag" label="状态" width="100" align="center">
            <template #default="scope">
              <el-tag :type="scope.row.delflag === 1 ? 'danger' : 'success'">
                {{ scope.row.delflag === 1 ? '已删除' : '正常' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="280" align="center">
            <template #default="scope">
              <el-button 
                v-if="scope.row.delflag !== 1"
                type="primary" 
                size="small" 
                @click="handleDownload(scope.row)"
              >
                下载
              </el-button>
              <el-button 
                v-if="scope.row.delflag !== 1"
                type="success" 
                size="small" 
                @click="handleExport(scope.row)"
              >
                导出文件
              </el-button>
              <el-button 
                v-if="scope.row.delflag !== 1"
                type="danger" 
                size="small" 
                @click="handleDelete(scope.row)"
              >
                删除
              </el-button>
              <span v-if="scope.row.delflag === 1">已删除</span>
            </template>
          </el-table-column>
        </el-table>
        
        <!-- 分页 -->
        <div class="pagination-section">
          <el-pagination
            v-model:current-page="pagination.currentPage"
            v-model:page-size="pagination.pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="pagination.total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Upload } from '@element-plus/icons-vue'
import fileApi from '../api/fileApi.js'

// 响应式数据
const loading = ref(false)
const templateList = ref([])
const searchKeyword = ref('')
const uploadRef = ref()

// 分页配置
const pagination = reactive({
  currentPage: 1,
  pageSize: 20,
  total: 0
})

// 上传配置 - 使用自定义上传处理
const uploadAction = '#'

// 模板数据将从API获取

// 获取模板列表
const getTemplateList = async () => {
  loading.value = true
  try {
    const params = {
      size: pagination.pageSize,
      currentPage: pagination.currentPage
    }
    
    if (searchKeyword.value) {
      params.filename = searchKeyword.value
    }
    
    const response = await fileApi.queryTemplateList(params)
    if (response.success===0) {
      templateList.value = response.data.data || []
      pagination.total = response.data.total || 0
    } else {
      ElMessage.error(response.message || '获取模板列表失败')
    }
    
  } catch (error) {
    console.error('获取模板列表失败:', error)
    ElMessage.error('获取模板列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.currentPage = 1
  getTemplateList()
}

// 分页大小改变
const handleSizeChange = (size) => {
  pagination.pageSize = size
  pagination.currentPage = 1
  getTemplateList()
}

// 当前页改变
const handleCurrentChange = (page) => {
  pagination.currentPage = page
  getTemplateList()
}

// 下载模板
const handleDownload = async (template) => {
  try {
    const response = await fileApi.downloadFile(template.id)
    
    // 创建下载链接
    const blob = new Blob([response])
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = template.file_name
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)
    
    ElMessage.success('下载成功')
  } catch (error) {
    console.error('下载失败:', error)
    ElMessage.error('下载失败')
  }
}

// 导出文件
const handleExport = (template) => {
  // 使用自定义事件来传递数据并切换菜单
  const event = new CustomEvent('templateExport', {
    detail: {
      templateId: template.id,
      templateName: template.file_name
    }
  })
  window.dispatchEvent(event)
  
  // 切换到材料导出菜单
  const menuEvent = new CustomEvent('menuSelect', {
    detail: { menuIndex: 'material-2' }
  })
  window.dispatchEvent(menuEvent)
}

// 删除模板
const handleDelete = async (template) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除模板 "${template.file_name}" 吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    
    const response = await fileApi.deleteTemplate(template.id)
    
    if (response.success === 0) {
      ElMessage.success('删除成功')
      getTemplateList()
    } else {
      ElMessage.error(response.message || '删除失败')
    }
    
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 上传前检查
const beforeUpload = (file) => {
  const isValidType = [
    'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
    'application/msword',
    'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    'application/vnd.ms-excel',
    'application/vnd.openxmlformats-officedocument.presentationml.presentation',
    'application/vnd.ms-powerpoint',
    'application/pdf'
  ].includes(file.type)
  
  if (!isValidType) {
    ElMessage.error('只能上传 Word、Excel、PowerPoint 或 PDF 文件!')
    return false
  }
  
  const isLt10M = file.size / 1024 / 1024 < 10
  if (!isLt10M) {
    ElMessage.error('文件大小不能超过 10MB!')
    return false
  }
  
  return true
}

// 自定义上传处理
const customUpload = async (options) => {
  try {
    const formData = new FormData()
    formData.append('file', options.file)
    
    const response = await fileApi.uploadTemplate(formData)
    
    if (response.success===0) {
      ElMessage.success('成功上传')
      getTemplateList()
    } else {
      ElMessage.error(response.message || '上传失败')
    }
  } catch (error) {
    console.error('上传失败:', error)
    ElMessage.error('上传失败')
  }
}

// 格式化时间
const formatDateTime = (timestamp) => {
  if (!timestamp) return '-'
  const date = new Date(timestamp)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

// 组件挂载时获取数据
onMounted(() => {
  getTemplateList()
})
</script>

<style scoped>
.template-manager-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.action-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 20px;
  background-color: #f8f9fa;
  border-radius: 8px;
}

.search-area {
  display: flex;
  align-items: center;
  gap: 10px;
}

.upload-area {
  display: flex;
  align-items: center;
}

.table-section {
  margin-top: 20px;
}

.pagination-section {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}
</style>
